import React from 'react';
import { withRouter } from 'react-router-dom';
import MarkdownIt from 'markdown-it';
import MdEditor from 'react-markdown-editor-lite';
import 'react-markdown-editor-lite/lib/index.css';
import axios from 'axios';
import { Input, Button, Select } from 'antd';
import 'antd/dist/antd.css';
import API from "@common/api.js";
import userStore from "../../common/userStore";

const { Option } = Select;

const selectBefore = (
  <Select defaultValue="动态：" className="select-before">
    <Option value="动态：">动态</Option>
    <Option value="提问：">提问</Option>
    <Option value="分享：">分享</Option>
    <Option value="建议：">建议</Option>
    <Option value="讨论：">讨论</Option>
    <Option value="其他：">其他</Option>
  </Select>
);

class UploadPost extends React.Component {
  constructor(props) {
    super(props);
    this.handleEditorChange = this.handleEditorChange.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
      md: {
        text: "",
        html: ""
      },
      title: ""
    }
    this.jumpToLogin = this.jumpToLogin.bind(this);
    userStore.subscribe(this.jumpToLogin);
    // if(!userStore.getState()['isLogin'])
    //     window.location.href = '/login';
  }

  jumpToLogin() {
      if(!userStore.getState()['isLogin'])
          window.location.href = '/login';
  }


  handleSubmit() {
    let form = new FormData();
    form.append("title", this.state.title);
    form.append("content", this.state.md['text']);
    Date.prototype.Format = function (fmt) { // author: meizz
      var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    }
    let now = new Date().Format("yyyy-MM-dd hh:mm:ss");
    let nowTime = now.toLocaleString();
    form.append("create_datetime", nowTime);
    console.log("Submitting!");
    API.uploadAPost(form).then((res) => {
      console.log("The test API result is:");
      console.log(res);
      // window.location.href = "/";
    });
    this.props.history.push("/");
  }

  handleEditorChange(mdChange) {
    console.log(mdChange);
    this.setState({
      md: mdChange
    });
  }

  handleTitleChange(e) {
    console.log(e.target.value)
    this.setState({
      title: e.target.value,
    })
  }

  onImageUpload(file) {
    console.log("file is:");
    console.log(file);
    var form = new FormData();
    form.append("file", file);
    return axios.post("http://localhost:8080/upload", form).then((res) => {
      console.log("The test API result is:");
      console.log(res);
      return res["data"];
    });

  }

  render() {
    const mdParser = new MarkdownIt(/* Markdown-it options */);
    return (<div style={{ width: '900px', margin: "auto" }}>
      <div style={{ margin: "10px" }}>
        <Input addonBefore={selectBefore} placeholder="请输入标题" style={{ width: '800px', height: "32px" }} value={this.state.title} onChange={this.handleTitleChange} />
        <Button style={{ float: "right" }} type="primary" onClick={this.handleSubmit}>发帖</Button>
      </div>
      <MdEditor style={{ height: '500px' }}
        renderHTML={text => mdParser.render(text)}
        onChange={this.handleEditorChange}
        onImageUpload={this.onImageUpload}
        value={this.state.md['text']}

      />
    </div>);
  }
}
export default withRouter(UploadPost);